package com.mindskip.xzs.controller.admin;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.PageInfo;
import com.mindskip.xzs.base.BaseApiController;
import com.mindskip.xzs.base.RestResponse;
import com.mindskip.xzs.base.SystemCode;
import com.mindskip.xzs.domain.Question;
import com.mindskip.xzs.domain.TextContent;
import com.mindskip.xzs.domain.User;
import com.mindskip.xzs.domain.UserEventLog;
import com.mindskip.xzs.domain.enums.QuestionTypeEnum;
import com.mindskip.xzs.domain.question.QuestionObject;
import com.mindskip.xzs.event.UserEvent;
import com.mindskip.xzs.exception.BusinessException;
import com.mindskip.xzs.repository.NewExamPaperQuestionCustomerAnswerMapper;
import com.mindskip.xzs.repository.NewTextContentMapper;
import com.mindskip.xzs.service.NewQuestionService;
import com.mindskip.xzs.service.QuestionService;
import com.mindskip.xzs.utility.*;
import com.mindskip.xzs.viewmodel.admin.question.QuestionBatchEditRequestVM;
import com.mindskip.xzs.viewmodel.admin.question.QuestionEditRequestVM;
import com.mindskip.xzs.viewmodel.admin.question.QuestionPageRequestVM;
import com.mindskip.xzs.viewmodel.admin.question.QuestionResponseVM;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController("AdminQuestionController")
@RequestMapping(value = "/api/admin/question")
public class QuestionController extends BaseApiController {

    private final QuestionService questionService;
    @Resource
    private NewTextContentMapper newTextContentMapper;
    @Resource
    private NewQuestionService newQuestionService;
    @Resource
    private ApplicationEventPublisher eventPublisher;

    @Autowired
    public QuestionController(QuestionService questionService) {
        this.questionService = questionService;
    }

    @RequestMapping(value = "/page", method = RequestMethod.POST)
    public RestResponse<PageInfo<QuestionResponseVM>> pageList(@RequestBody QuestionPageRequestVM model) {
        if (model.getScore() != null) {
            model.setScore(String.valueOf(ExamUtil.scoreFromVM(model.getScore())));
        }
        PageInfo<Question> pageInfo = questionService.page(model);
        PageInfo<QuestionResponseVM> page = PageInfoHelper.copyMap(pageInfo, q -> {
            QuestionResponseVM vm = modelMapper.map(q, QuestionResponseVM.class);
            vm.setCreateTime(DateTimeUtil.dateFormat(q.getCreateTime()));
            vm.setScore(ExamUtil.scoreToVM(q.getScore()));
            TextContent textContent = newTextContentMapper.selectById(q.getInfoTextContentId());
            QuestionObject questionObject = JsonUtil.toJsonObject(textContent.getContent(), QuestionObject.class);
            String clearHtml = HtmlUtil.clear(questionObject.getTitleContent());
            vm.setShortTitle(clearHtml);
            return vm;
        });
        return RestResponse.ok(page);
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public RestResponse edit(@RequestBody @Valid QuestionEditRequestVM model) {
        RestResponse validQuestionEditRequestResult = validQuestionEditRequestVM(model);
        if (validQuestionEditRequestResult.getCode() != SystemCode.OK.getCode()) {
            return validQuestionEditRequestResult;
        }

        if (null == model.getId()) {
            questionService.insertFullQuestion(model, getCurrentUser().getId());
        } else {
            questionService.updateFullQuestion(model);
        }

        newQuestionService.updateCategorysInCache();
        return RestResponse.ok();
    }

    @RequestMapping(value = "/batchEdit", method = RequestMethod.POST)
    public RestResponse batchEdit(@RequestBody @Valid QuestionBatchEditRequestVM model) {
        ArrayList<Question> questions = new ArrayList<>();
        for (Integer questionId : model.getIds()) {
            Question question = new Question();
            question.setId(questionId);
            if (StringUtils.isNotBlank(model.getCategory())) {
                question.setCategory(model.getCategory());
            }
            if (StringUtils.isNotBlank(model.getScore())) {
                question.setScore(ExamUtil.scoreFromVM(model.getScore()));
            }
            if (model.getDifficult() != null) {
                question.setDifficult(model.getDifficult());
            }
            questions.add(question);
        }
        newQuestionService.updateBatchById(questions);
        return RestResponse.ok("批量操作成功");
    }

    @RequestMapping(value = "/select/{id}", method = RequestMethod.POST)
    public RestResponse<QuestionEditRequestVM> select(@PathVariable Integer id) {
        QuestionEditRequestVM newVM = questionService.getQuestionEditRequestVM(id);
        return RestResponse.ok(newVM);
    }

    /**
     * 查询题目分类列表
     */
    @RequestMapping(value = "/select/categorys", method = RequestMethod.GET)
    public RestResponse<List<String>> selectCategory(@RequestParam(required = false, value = "keyword") String keyword) {
        return RestResponse.ok(newQuestionService.queryCategoryListInCache(keyword));
    }


    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    public RestResponse delete(@PathVariable Integer id) {
        Question question = questionService.selectById(id);
        if (question == null) {
            throw new BusinessException("删除问题不存在");
        }
        // 删除关联试卷答案
/*        List<ExamPaperQuestionCustomerAnswer> examPaperQuestionCustomerAnswers = newExamPaperQuestionCustomerAnswerMapper.selectList(
                new LambdaQueryWrapper<ExamPaperQuestionCustomerAnswer>()
                        .eq(ExamPaperQuestionCustomerAnswer::getQuestionId, id)
        );
        if (CollectionUtil.isNotEmpty(examPaperQuestionCustomerAnswers)) {
            newTextContentMapper.delete(
                    new LambdaQueryWrapper<TextContent>()
                            .in(TextContent::getId, examPaperQuestionCustomerAnswers.stream().map(ExamPaperQuestionCustomerAnswer::getTextContentId).collect(Collectors.toList()))
            );
            newExamPaperQuestionCustomerAnswerMapper.delete(
                    new LambdaQueryWrapper<ExamPaperQuestionCustomerAnswer>()
                            .in(ExamPaperQuestionCustomerAnswer::getId, examPaperQuestionCustomerAnswers.stream().map(ExamPaperQuestionCustomerAnswer::getId).collect(Collectors.toList()))
            );
        }*/
        newQuestionService.updateById(question.setDeleted(true).setStatus(0));
        newQuestionService.updateCategorysInCache();

        // 记录日志
        User user = getCurrentUser();
        UserEventLog userEventLog = new UserEventLog(user.getId(), user.getUserName(), user.getRealName(), new Date());
        String content = String.format("%s删除编号为【%s】的试题", user.getUserName(), question.getId());
        userEventLog.setContent(content);
        eventPublisher.publishEvent(new UserEvent(userEventLog));

        return RestResponse.ok();
    }

    private RestResponse validQuestionEditRequestVM(QuestionEditRequestVM model) {
        int qType = model.getQuestionType().intValue();
        boolean requireCorrect = qType == QuestionTypeEnum.SingleChoice.getCode() || qType == QuestionTypeEnum.TrueFalse.getCode();
        if (requireCorrect) {
            if (StringUtils.isBlank(model.getCorrect())) {
                String errorMsg = ErrorUtil.parameterErrorFormat("correct", "不能为空");
                return new RestResponse<>(SystemCode.ParameterValidError.getCode(), errorMsg);
            }
        }

        if (qType == QuestionTypeEnum.GapFilling.getCode()) {
            Integer fillSumScore = model.getItems().stream().mapToInt(d -> ExamUtil.scoreFromVM(d.getScore())).sum();
            Integer questionScore = ExamUtil.scoreFromVM(model.getScore());
            if (!fillSumScore.equals(questionScore)) {
                String errorMsg = ErrorUtil.parameterErrorFormat("score", "空分数和与题目总分不相等");
                return new RestResponse<>(SystemCode.ParameterValidError.getCode(), errorMsg);
            }
        }
        return RestResponse.ok();
    }
}
